package dao

import (
	"fmt"
	"hft/Database/admin"
	"hft/Http/Models/request"
	utils "hft/Http/Utils"
	"regexp"

	"gorm.io/gorm"
)

type LouPanName struct{}

func (l *LouPanName) IsHasUse(hasUse int, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if hasUse == 1 || hasUse == 2 {
			return db.Where("has_use = ?", hasUse)
		} else {
			return db
		}
	}
}

func (l *LouPanName) RegionLike(regionLink string, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Where("region_link LIKE ?", fmt.Sprintf("%v%%", regionLink))
	}
}

func (l *LouPanName) NameLike(name string, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if name == "" {
			return db
		} else {
			return db.Where("name LIKE ?", fmt.Sprintf("%%%v%%", name))
		}
	}
}

func (l *LouPanName) GetLouPanNameList(paginate *request.LouPanNamePage, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Scopes(l.IsHasUse(paginate.HasUse, db)).Scopes(l.RegionLike(paginate.RegionLink, db)).Scopes(Paginate(Page(paginate.Page), db))
	}
}

func (l *LouPanName) GetLouNameByAccount(paginate *request.LouNameAccountPage, db *gorm.DB) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		return db.Scopes(l.NameLike(paginate.Name, db)).Scopes(Paginate(Page(paginate.Page), db))
	}
}

// 处理楼盘分页以及名字搜索
func (l *LouPanName) SearchLouPanNameList(paginate *request.LouNameAccountPage, list []*admin.LouPanName) (newList []*admin.LouPanName, total int64) {

	name := utils.DeleteStringSpace(paginate.Name)

	var start, end = PageDao.PageOpera(Page(paginate.Page))

	if name == "" {

		if end > len(list) {
			end = len(list)
		}

		return list[start:end], int64(len(list) - 1)
	}

	var newNameList []*admin.LouPanName

	for _, v := range list {

		match, _ := regexp.MatchString(name, v.Name)

		if match {
			newNameList = append(newNameList, v)
		}

	}

	if end > len(newNameList) {
		end = len(newNameList)
	}

	return newNameList[start:end], int64(len(newNameList) - 1)

}

var LouPanNameDao = new(LouPanName)
